// index.js
const request=require('../../util/request.js')

Page({
  data: {
      list:[],
      showstring:0,
      showSelList:false,
      showAddType:false,
      getOnclick:[],
      FNo:'',
      FDate:'',
      Id:'',
  },

  onLoad(event) {
    console.log(event,"eventttttttt")
    this.setData({
      FNo:event.tmp1,
      FDate:event.tmp2,
      Id:event.tmp3,
    })
  },
  onShow() {
    // if (this.data.pendingData) {
    //   this.onSubmitSuccess(this.data.pendingData);
    //   this.setData({ pendingData: null });
    // }
  },

  onReady() {

  },

  scanCode(e){
    console.log(e,"用户点击扫码")
    var that = this
    that.setData({
      showAddType:!that.data.showAddType
    })
    wx.scanCode({
      onlyFromCamera: false, // 允许从相册选择
      scanType: ['barCode'],  // 修改为识别条形码
      success: (res) => {
        console.log(res,"成功")
        console.log(res.result,"成功")
        const barcodeContent = res.result; // 获取条形码内容
        that.getList(barcodeContent)
        
      },
      fail: (err) => {
        console.log(err,"失败")
        let errorMsg = '扫码失败'
        switch(err.errMsg) {
          case 'scanCode:fail':
            errorMsg = '无法识别该条形码，请尝试：\n1. 调整光线\n2. 对准条形码\n3. 确保条形码清晰'
            break;
          case 'scanCode:cancel':
            errorMsg = '已取消扫码'
            return;
          default:
            errorMsg = `扫码失败: ${err.errMsg}`
        }
        wx.showModal({
          title: '提示',
          content: errorMsg,
          showCancel: false
        })
      }
    });
  },

  get_report_works(){
    wx.navigateTo({ url: '/pages/get_report_works/get_report_works' })
  },

  get_barcode_list(){
    wx.navigateTo({ url: '/pages/get_barcode_list/get_barcode_list' })
  },

  towork(){
    wx.navigateTo({ url: '/pages/baogong/baogong' })
  },

  set_bao_gong(){
    wx.navigateTo({ url: '/pages/set_bao_gong/set_bao_gong' })
  },

  getList(e){
    var that = this;
      let tmp = {
        code:e
      }
    request.requestGet('fruit/get_barcode_info', tmp, "加载中",function (res) {
      console.log(res,"resssssssss")
      that.setData({showstring:res.status})
      if(res.status === 200){
        // that.setData({
        //   list:res.data
        // })
        let currentList = that.data.list || [];
        let newData = res.data;
        
        // 如果返回的是数组，遍历处理；如果是单个对象，转为数组处理
        if (!Array.isArray(newData)) {
          newData = [newData];
        }
        
        // 创建当前列表中所有barcode的集合
        let existingBarcodes = new Set();
        currentList.forEach(item => {
          if (item && item.barcode) {
            existingBarcodes.add(item.barcode);
          }
        });
        
        // 过滤出不存在的新数据
        let dataToAdd = newData.filter(item => {
          return item && item.barcode && !existingBarcodes.has(item.barcode);
        });
        
        // 将新数据添加到列表中
        if (dataToAdd.length > 0) {
          that.setData({
            list: [...currentList, ...dataToAdd]
          });
        } else {
          // 如果没有新数据，可以给用户一个提示
          wx.showToast({
            title: '该商品已存在',
            icon: 'none'
          });
        }
      }else if(res.status === 400){
        that.setData({showstring:res.msg})
      }
      }, function (res) {
        console.log(res,"请求失败")
      },
    )
  },
  set_worker(){
    wx.navigateTo({ url: '/pages/baogongren/baogongren' })
  },

  showSel(e){
    var that = this
    this.setData({
      showSelList:!that.data.showSelList
    })
  },

  showAdd(e){
    var that = this
    this.setData({
      showAddType:!that.data.showAddType
    })
  },

  onReturnFromPageB(getdata) {
    const currentData = this.data.getOnclick || []
    const existingIds = new Set(currentData.map(item => item.FId))
    const newData = getdata.filter(item => !existingIds.has(item.FId))
    const mergedData = [...currentData, ...newData]
    this.setData({getOnclick: mergedData})
  },

  del(e){
    let tmpList = this.data.getOnclick
    for(let i = 0;i<tmpList.length;i++){
      if(tmpList[i].FId === e.currentTarget.dataset.index){
        tmpList.splice(i,1)
        break
      }
    }
    this.setData({getOnclick:tmpList})
  },

  submit(){
    //提交 参数={"wids":[员工FId，员工FID],"fids":[条码fid]}
    let wids1 = []
    for(let i = 0;i<this.data.getOnclick.length;i++){
      wids1.push(this.data.getOnclick[i].FId);
    }
    let fids1 = []
    for(let i = 0;i<this.data.list.length;i++){
      fids1.push(this.data.list[i].fid);
    }
    let tmpList = {
      wids:wids1,
      fids:fids1
    }
    request.requestAjax('fruit/save_reporting_work',tmpList,"提交中",function(res){
      if(res.status==200){
        wx.showToast({
          title: '操作成功',
          icon: 'success',
          duration: 1000,
          success: function() {
            setTimeout(function() {
              wx.navigateBack() 
            }, 1000);
          }
        });
        return false;
      }else{
        wx.showToast({
          title: res.msg,
          icon:'none'
        });
      }
    },function(res){
      wx.showToast({
        title: "登录失败",
        icon:'none'
      });
    },false)
  },

  to_get_barcode_list(){
    var that = this
    wx.navigateTo({ url: '/pages/get_barcode_list/get_barcode_list' })
    // this.setData({
    //   showAddType:!that.data.showAddType
    // })
  },

  onSubmitSuccess(data){
    console.log("方法开始执行，传入数据：", data);
    
    const newDataList = Array.isArray(data) ? data : [data];
    console.log("处理后的新数据列表：", newDataList);
    
    const currentList = this.data.list || [];
    console.log("当前列表：", currentList, "长度：", currentList.length);
    
    const existingBarcodes = new Set();
    currentList.forEach((item, index) => {
      console.log(`当前列表第${index}项：`, item, "条码：", item?.barcode);
      if (item && item.barcode) {
        existingBarcodes.add(item.barcode);
      }
    });
    
    console.log("现有条码集合：", Array.from(existingBarcodes));
    
    const dataToAdd = newDataList.filter(item => {
      const shouldAdd = item && item.barcode && !existingBarcodes.has(item.barcode);
      console.log(`条码 ${item?.barcode} 是否添加：${shouldAdd}`);
      return shouldAdd;
    });
    
    console.log("最终要添加的数据：", dataToAdd);
    console.log("要添加的数据数量：", dataToAdd.length);
    
    if (dataToAdd.length > 0) {
      const updatedList = [...currentList, ...dataToAdd];
      
      // 使用 setData 的回调确保完整执行:ml-citation{ref="1" data="citationList"}
      this.setData({
        list: updatedList
      }, () => {
        // 在 setData 完成后执行，确保插入完整数据:ml-citation{ref="3" data="citationList"}
        console.log('新增数据：', dataToAdd);
        console.log('更新后列表：', updatedList);
        console.log('当前data.list：', this.data.list);
        
        wx.showToast({
          title: `成功添加${dataToAdd.length}条数据`,
          icon: 'success',
          duration: 2000
        });
        
        // 如果有 getList 方法，确保在数据更新后调用
        if (this.getList && typeof this.getList === 'function') {
          this.getList();
        }
      });
    } else {
      console.log("没有需要添加的数据，原因分析：");
      console.log("- 新数据条码：", newDataList.map(item => item.barcode));
      console.log("- 现有条码：", Array.from(existingBarcodes));
      console.log("- 重复条码：", newDataList.filter(item => existingBarcodes.has(item.barcode)).map(item => item.barcode));
      
      wx.showToast({
        title: '没有新增数据（可能已存在）',
        icon: 'none',
        duration: 1500
      });
    }
  }


})

